package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"log"
	"net/http"
	"time"
)

func main() {

	//启动grpc服务端
	//server := grpc.NewServer()
	//proto.RegisterTestServer(server, &service.Service{})
	//port := GenFreePort()
	//listen, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	//if err != nil {
	//	log.Fatalf("监听端口:%d失败: %s", port, err.Error())
	//}

	//启动http服务的
	r := gin.Default()
	//路由
	v1 := r.Group("/v1")
	{
		v1.GET("/welcome/say", func(c *gin.Context) {
			name := c.DefaultQuery("name", "Guest")
			c.String(http.StatusOK, "Hello %s ", name)
		})
	}

	// The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe
	s := http.Server{
		Addr:           "192.168.12.111:9999",
		Handler:        r,
		ReadTimeout:    20 * time.Second,
		WriteTimeout:   20 * time.Second,
		MaxHeaderBytes: 1 << 20, //1M
	}

	// 创建serverConfig
	// 支持多个;至少一个ServerConfig
	serverConfig := []constant.ServerConfig{
		{
			IpAddr: "192.168.14.23",
			Port:   8848,
		},
	}

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}

	// 创建服务发现客户端的另一种方式 (推荐)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfig,
		},
	)
	if err != nil {
		log.Fatalf("初始化nacos失败: %s", err.Error())
	}
	success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          "192.168.12.111",
		Port:        uint64(9999),
		ServiceName: "bmm-http-server",
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"name": "test"},
		ClusterName: "DEFAULT",       // 默认值DEFAULT
		GroupName:   "DEFAULT_GROUP", // 默认值DEFAULT_GROUP
	})
	if err != nil {
		log.Fatalf("注册服务失败: %s", err.Error())
	}

	log.Println("success: ", success)
	log.Printf("服务启动成功;PORT:%d\n", 9999)

	//gprc
	//_ = server.Serve(listen)

	//http
	error := s.ListenAndServe()
	if error != nil {
		fmt.Printf("服务启动出错 %s", error)
	} else {
		fmt.Printf("http服务启动成功")
	}

}
